const express = require('express');
const path = require('path');
// const favicon = require('serve-favicon');
const logger = require('morgan');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
// webpack dev middleware
const webpack = require('webpack');
const webpackDevMiddleware = require('webpack-dev-middleware');

const config = require('./config/webpack.config.js');

const compiler = webpack(config);

const index = require('./routes/index');
const users = require('./routes/users');
const api = require('./routes/api');

const app = express();

// Tell express to use the webpack-dev-middleware and use the webpack.config.js
// configuration file as a base.
app.use(webpackDevMiddleware(compiler, {
  publicPath: config.output.publicPath,
}));

// view engine setup
app.set('views', path.join(__dirname, 'dist/views'));
app.set('view engine', 'hbs');

require('./hbs.conf.js');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'dist/public')));

app.use('/', index);
app.use('/users', users);
app.use('/api', api);

// catch 404 and forward to error handler
app.use((req, res, next) => {
  console.log('**************出错了********************');
  const err = new Error('Not Found');
  err.status = 404;
  next(err);
  console.log('**************没有next？********************');
});

// error handler
app.use((err, req, res, next) => {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};
  console.log('出错了********************');
  // render the error page
  res.status(err.status || 500);
  res.render('error/error');
});

module.exports = app;
